/**
 * 时间格式化工具
 * @type {{parseTime: timeUtil.parseTime, formatTime: timeUtil.formatTime}}
 * @Usage
 * 列表中的转换 parseTime: {{scope.row.created | parseTime('{y}-{m}-{d} {h}:{i}')}}
 * 详细页面 parseTime: created=parseTime(created, '{y}-{m}-{d} {h}:{i}')
 */
let timeUtil = {
  parseTime: function (time, cFormat) {
    if (time === null) {
      return null
    }
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (('' + time).length === 10) time = parseInt(time) * 1000
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return timeStr
  },
  formatTime: function (time, option) {
    time = +time * 1000
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
      return '刚刚'
    } else if (diff < 3600) { // less 1 hour
      return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
      return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
      return '1天前'
    }
    if (option) {
      return this.parseTime(time, option)
    } else {
      return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
    }
  },
  monthsToNow: function (time) {
    return parseInt((new Date().getTime() - time) / (84600 * 30 * 1000))
  }
}

/**
 * Url 解析
 * @type {{urlParse: URLUtil.urlParse, paramsJson: URLUtil.paramsJson}}
 */
let urlUtil = {
  /**
   * [解析url参数]
   * @example ?id=12345&a=1
   * @return Object {id:12345,a:1}
   */
  urlParse: function () {
    let url = decodeURIComponent(window.location.search)
    let obj = {}
    let reg = /[?&][^?&]+=[^?&]+/g
    // ['?id=12345','a=1']
    let arr = url.match(reg)
    if (arr) {
      arr.forEach((item) => {
        let tempArr = item.substring(1).split('=')
        let key = decodeURIComponent(tempArr[0])
        let value = decodeURIComponent(tempArr[1])
        obj[key] = value
      })
    }
    return obj
  },
  /**
   * [解析url参数]
   * @example ?id=12345&a=1
   * @returns Object {id: "12345", a: "1"}
   */
  paramsJson: function () {
    let url = location.search
    let paramArray = []
    if (url.indexOf('?') !== -1) {
      let str = url.substr(1)
      let strs = str.split('&')
      for (let i = 0; i < strs.length; i++) {
        paramArray[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
      }
    }
    return paramArray
  }
}

let stringUtil = {
  isEmpty: function (input) {
    return input == null || input === '' || input === undefined
  },
  isNotEmpty: function (input) {
    return !this.isEmpty(input)
  },
  isBlank: function (input) {
    return input == null || /^\s*$/.test(input)
  },
  isNotBlank: function (input) {
    return !this.isBlank(input)
  },
  trim: function (input) {
    return input.replace(/^\s+|\s+$/, '')
  },
  trimToEmpty: function (input) {
    return input == null ? '' : this.trim(input)
  },
  startsWith: function (input, prefix) {
    return input.indexOf(prefix) === 0
  },
  endsWith: function (input, suffix) {
    return input.lastIndexOf(suffix) === 0
  },
  contains: function (input, searchSeq) {
    return input.indexOf(searchSeq) >= 0
  },
  equals: function (input1, input2) {
    return input1 === input2
  },
  equalsIgnoreCase: function (input1, input2) {
    return input1.toLocaleLowerCase() === input2.toLocaleLowerCase()
  },
  containsWhitespace: function (input) {
    return this.contains(input, ' ')
  },
  // 生成指定个数的字符
  repeat: function (ch, repeatTimes) {
    let result = ''
    for (let i = 0; i < repeatTimes; i++) {
      result += ch
    }
    return result
  },
  deleteWhitespace: function (input) {
    return input.replace(/\s+/g, '')
  },
  rightPad: function (input, size, padStr) {
    return input + this.repeat(padStr, size)
  },
  leftPad: function (input, size, padStr) {
    return this.repeat(padStr, size) + input
  },
  // 首小写字母转大写
  capitalize: function (input) {
    if (input == null || (input.length) === 0) {
      return input
    }
    return input.replace(/^[a-z]/, function (matchStr) {
      return matchStr.toLocaleUpperCase()
    })
  },
  // 首大写字母转小写
  uncapitalize: function (input) {
    if (input == null || (input.length) === 0) {
      return input
    }
    return input.replace(/^[A-Z]/, function (matchStr) {
      return matchStr.toLocaleLowerCase()
    })
  },
  // 大写转小写，小写转大写
  swapCase: function (input) {
    return input.replace(/[a-z]/ig, function (matchStr) {
      if (matchStr >= 'A' && matchStr <= 'Z') {
        return matchStr.toLocaleLowerCase()
      } else if (matchStr >= 'a' && matchStr <= 'z') {
        return matchStr.toLocaleUpperCase()
      }
    })
  },
  // 统计含有的子字符串的个数
  countMatches: function (input, sub) {
    if (this.isEmpty(input) || this.isEmpty(sub)) {
      return 0
    }
    let count = 0
    let index = 0
    while ((index = input.indexOf(sub, index)) !== -1) {
      index += sub.length
      count++
    }
    return count
  }
}

let decimalUtil = {
  add: function (a, b) {
    let c, d, e
    try {
      c = String(a).split('.')[1].length
    } catch (f) {
      c = 0
    }
    try {
      d = String(b).split('.')[1].length
    } catch (f) {
      d = 0
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
  },

  mul: function (a, b) {
    let c = 0
    const d = String(a)
    const e = String(b)
    try {
      c += d.split('.')[1].length
    } catch (f) {
    }
    try {
      c += e.split('.')[1].length
    } catch (f) {
    }
    return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)
  },
  sub: function (a, b) {
    let c, d, e
    try {
      c = String(a).split('.')[1].length
    } catch (f) {
      c = 0
    }
    try {
      d = String(b).split('.')[1].length
    } catch (f) {
      d = 0
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
  },

  div: function (a, b) {
    let c
    let d
    let e = 0
    let f = 0
    try {
      e = String(a).split('.')[1].length
    } catch (g) {
    }
    try {
      f = String(b).split('.')[1].length
    } catch (g) {
    }
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
  },

  // 金额千分位转换
  moneyFormat: function (num) {
    if (num == null || num === '') {
      return ''
    }
    let res = String(num).replace(/\d+/, function (n) { // 先提取整数部分
      return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
        return $1 + ','
      })
    })
    if (res.indexOf('.') === -1) {
      res = res + '.00'
    }
    if (res.split('.')[1].length === 1) {
      res = res + '0'
    }
    return res
  }
}

export {timeUtil, urlUtil, stringUtil, decimalUtil}
